package com.xxl.sso.server.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.xxl.sso.core.conf.Conf.ThethirdConstant;
import com.xxl.sso.core.data.SsSsoCacheData;
import com.xxl.sso.core.entity.thethird.ThirdWebsiteInfo;
import com.xxl.sso.core.login.SsoTokenLoginHelper;
import com.xxl.sso.core.login.SsoWebLoginHelper;
import com.xxl.sso.core.login.session.SessionManager;
import com.xxl.sso.core.user.XxlSsoUser;
import com.xxl.sso.server.core.model.UserInfo;
import com.xxl.sso.server.core.result.ReturnT;
import com.xxl.sso.server.service.UserService;

/**
 * sso server (for web)
 *
 * @author xuxueli 2017-08-01 21:39:47
 */
@Controller
public class WebController {
    @Autowired
    private UserService userService;

    @RequestMapping("/")
    public String index(Model model, HttpServletRequest request, HttpServletResponse response) {
        model.addAttribute("thethirdSystemMap", SsSsoCacheData.thethirdSystemMap);
        return "index";
    }

    /**
     * Login page
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping("/login")
    public String login(Model model, RedirectAttributes redirectAttributes, HttpServletRequest request, HttpServletResponse response) {
        String systemId = request.getParameter(ThethirdConstant.SSO_THETHIRD_IN_PARAMS_SYSTEM_ID);
        model.addAttribute(ThethirdConstant.SSO_THETHIRD_IN_PARAMS_SYSTEM_ID, systemId);

        // login check
        XxlSsoUser xxlUser = SsoWebLoginHelper.loginCheck(request, response);

        if (xxlUser != null) {
            ThirdWebsiteInfo thirdWebsiteInfo = SsSsoCacheData.thethirdSystemMap.get(systemId);

            if (thirdWebsiteInfo != null) {
                String accessToken = xxlUser.getAccessToken();

                String redirectUrl = thirdWebsiteInfo.getCallbackUrl();
                if (redirectUrl!=null && redirectUrl.trim().length() > 0) {
                    redirectAttributes.addAttribute(ThethirdConstant.SSO_ACCESS_TOKEN, accessToken);
                    return "redirect:" + redirectUrl;
                } else {
                    return "redirect:/";
                }
            } else {
                return "redirect:/error";
            }
        }

        model.addAttribute("errorMsg", request.getParameter("errorMsg"));
        return "login";
    }

    /**
     * Login
     *
     * @param request
     * @param redirectAttributes
     * @param username
     * @param password
     * @return
     */
    @RequestMapping("/doLogin")
    public String doLogin(HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes, String username, String password, String ifRemember) {
        String systemId = request.getParameter(ThethirdConstant.SSO_THETHIRD_IN_PARAMS_SYSTEM_ID);
        redirectAttributes.addAttribute(ThethirdConstant.SSO_THETHIRD_IN_PARAMS_SYSTEM_ID, systemId);

        ThirdWebsiteInfo thirdWebsiteInfo = SsSsoCacheData.thethirdSystemMap.get(systemId);

        if (thirdWebsiteInfo != null) {
            boolean ifRem = (ifRemember != null && "on".equals(ifRemember)) ? true : false;

            ReturnT<UserInfo> result = userService.findUser(username, password);
            if (result.getCode() != ReturnT.SUCCESS_CODE) {
                redirectAttributes.addAttribute("errorMsg", result.getMsg());
                return "redirect:/login";
            }

            String userId = String.valueOf(result.getData().getUserid());

            XxlSsoUser xxlUser = SsoWebLoginHelper.loginCheckByUserId(userId, request, response);

            String accessToken = "";
            if (xxlUser == null) {
                accessToken = SsoWebLoginHelper.login(request, response, userId, username, ifRem);
            } else {
                accessToken = xxlUser.getAccessToken();
                SsoTokenLoginHelper.updateAccessTokenUserIdMap(accessToken, userId);
            }

            SessionManager.put(accessToken, request.getSession());

            String redirectUrl = thirdWebsiteInfo.getCallbackUrl();
            if (redirectUrl != null && redirectUrl.trim().length() > 0) {
                redirectAttributes.addAttribute(ThethirdConstant.SSO_ACCESS_TOKEN, accessToken);
                return "redirect:" + redirectUrl;
            } else {
                return "redirect:/";
            }
        }

        return "redirect:/error";
    }
}